#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Created on 2022-03-31 15:48:59
@author: DengLibin 榆霖
@description: 识别手写数字
'''
from os import listdir

import numpy as np

from kNN import classify0


def img2vector(file_path):
    """
    读取文件，转为向量

    Args:
        file_path (_type_): 文件路径
    """
    return_vec = np.zeros([1, 1024])
    with open(file_path) as f:
        index = 0
        # 32行
        for _ in range(32):
            line = f.readline()
            line = line.strip()
            for j in line:
                return_vec[0, index] = int(j)
                index += 1
    return return_vec


def hand_writing_class_test():
    """数字识别
    """
    hw_labels = []
    # 列出指定目录下的文件（文件夹） 名称
    training_file_list = listdir('trainingDigits')
    # 共多少个样本
    m = len(training_file_list)
    # 文本是32行32列 所以共1024个
    traing_mat = np.zeros([m, 1024])
    for i in range(m):
        file_name = training_file_list[i]
        # 当前文件对应的数字
        num = int(file_name.split('_')[0])
        # 放到label中
        hw_labels.append(num)
        # 第i行
        traing_mat[i, :] = img2vector('trainingDigits/%s' % file_name)

    # 测试集
    test_file_list = listdir('testDigits')
    # 错误数
    error_count = 0
    # 行数
    m_test = len(test_file_list)
    for i in range(m_test):
        test_file_name = test_file_list[i]
        test_num = int(test_file_name.split('_')[0])
        test_mat = img2vector('testDigits/%s' % test_file_name)
        # 使用knn算法识别
        result = classify0(test_mat, traing_mat, hw_labels, 5)
        print("识别结果%d, 真实结果%d" % (result, test_num))
        if result != test_num:
            error_count += 1
            
    print("错误数:%d,错误率:%f" % (error_count, error_count/m_test))

if __name__ == '__main__':
   hand_writing_class_test()
